<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 易而优团队 by 陈风任 <491085389@qq.com>
 * Date: 2021-01-14
 */

namespace app\admin\model;

use think\Db;
use think\Page;
use app\common\logic\ArctypeLogic;

/**
 * 商城模型
 */
load_trait('controller/Jump');
class ShopModel
{
    use \traits\controller\Jump;

    // 构造函数
    public function __construct($channeltype = 2)
    {
        // 时间戳
        $this->times = getTime();
        // 执行方法
        $this->action = 'insert';
        // 接收参数
        $this->paramArr = input('param.');
        // 模型ID，默认2(商城模型)
        $this->channeltype = intval($channeltype);
        // 数据表
        $this->arctype_db = Db::name('arctype');
        // 全局分类业务层
        $this->arctypeLogic = new ArctypeLogic();
    }

    // 商品分类操作
    public function goodsClassifyAction($action = '')
    {
        // 定义执行方法
        $this->action = $action;

        // 删除分类
        if ('delete' == $this->action) {
            $this->deleteGoodsClassifyData();
        }
        // 新增 or 编辑
        else {
            // 获取商品分类数据
            $resultArr = $this->getGoodsClassifyData();
            // dump($resultArr);exit;
            // 新增分类
            if ('insert' == $this->action) {
                $resultID = $this->arctype_db->insertGetId($resultArr);
                if (!empty($resultID)) {
                    model('AuthRole')->syn_auth_role($resultID);
                    \think\Cache::clear("arctype");
                    $this->success('保存成功', url('ShopProduct/arctype_index'));
                }
            }
            // 编辑分类
            else if ('update' == $this->action && !empty($this->paramArr['id'])) {
                $resultID = $this->arctype_db->where('id', intval($this->paramArr['id']))->update($resultArr);
                if (!empty($resultID)) {
                    \think\Cache::clear("arctype");
                    $this->success('保存成功', url('ShopProduct/arctype_index'));
                }
            }
        }
        $this->error('操作失败');
    }

    // 获取分类列表
    public function getGoodsClassifyList()
    {
        // 分类列表
        $where = [
            'is_del' => 0,
            'current_channel' => 2
        ];
        $arctype_list = $this->arctypeLogic->arctype_list(0, 0, false, 0, $where, false);

        // 获取所有有子栏目的栏目id
        $where = [
            'is_del' => 0,
            'parent_id' => ['gt', 0]
        ];
        $parent_ids = $this->arctype_db->where($where)->group('parent_id')->cache(true, EYOUCMS_CACHE_TIME, 'arctype')->column('parent_id');
        $cookied_treeclicked =  json_decode(cookie('admin-treeClicked-Arr'));
        empty($cookied_treeclicked) && $cookied_treeclicked = [];
        $all_treeclicked = cookie('admin-treeClicked_All');
        empty($all_treeclicked) && $all_treeclicked = [];
        $tree = [
            'has_children'=>!empty($parent_ids) ? 1 : 0,
            'parent_ids'=>json_encode($parent_ids),
            'all_treeclicked'=>$all_treeclicked,
            'cookied_treeclicked'=>$cookied_treeclicked,
            'cookied_treeclicked_arr'=>json_encode($cookied_treeclicked),
        ];
        // --- end

        // 生成静态所需参数
        $typeurl = '';
        $seo_pseudo = tpCache('global.seo_pseudo');//URL模式
        $sitemap_zzbaidutoken = config('tpcache.sitemap_zzbaidutoken');//实时推送Url的token
        $bdminipro = Db::name('weapp')->where(['code'=>'BdDiyminipro','status'=>1])->find();
        if (!empty($this->paramArr['typeid'])){
            $typeData = $this->arctype_db->where('id', $this->paramArr['typeid'])->find();
            if (!empty($typeData)) $typeurl = get_typeurl($typeData);
        }
        $eyou = [
            'handle' => !empty($this->paramArr['handle']) ? $this->paramArr['handle'] : '',
            'typeurl' => $typeurl,
            'bdminipro' => !empty($bdminipro) ? $bdminipro : [],
            'seo_pseudo' => $seo_pseudo,
            'zzbaidutoken' => $sitemap_zzbaidutoken,
        ];
        // --- end

        // 返回数据
        return [
            // 栏目cookie
            'tree' => $tree,
            // 生成静态所需参数
            'eyou' => $eyou,
            // 分类列表
            'arctype_list' => !empty($arctype_list) ? $arctype_list : [],
            // 回收站开关
            'recycle_switch' => tpSetting('recycle.recycle_switch'),
            // 模型列表
            'channeltype_list' => getChanneltypeList(),
            // 分类最多级别
            'arctype_max_level' => intval(config('global.arctype_max_level')),
            // 栏目ID
            'typeid' => !empty($this->paramArr['typeid']) ? intval($this->paramArr['typeid']) : 0,
            // 是否伪删除(回收站)
            'is_del' => !empty($this->paramArr['is_del']) ? intval($this->paramArr['is_del']) : 0,
        ];
    }

    // 获取页面所需数据
    public function getGoodsClassifyPublic($action = 'insert')
    {
        $arctype = [];
        if ('update' == $action) {
            // 分类ID
            if (empty($this->paramArr['id'])) $this->error('请选择分类');
            $where = [
                'a.id' => intval($this->paramArr['id']),
                'a.status' => 1,
                'a.is_del' => 0,
                'a.is_hidden' => 0,
            ];
            $field = 'a.*, b.link_names, b.host_id';
            $arctype = $this->arctype_db->alias('a')->join('__AD_LINK__ b', 'a.ad_link_id = b.link_id', 'LEFT')->field($field)->where($where)->find();
            $data = get_ad_link_url([$arctype]);
            $arctype = !empty($data) ? current($data) : [];
        }

        // 父级分类ID
        $parent_id = !empty($arctype['parent_id']) ? intval($arctype['parent_id']) : intval($this->paramArr['parent_id']);

        // 目录存放HTML路径
        $predirpath = $this->arctype_db->where(['id' => intval($parent_id)])->getField('dirpath');

        // 商品一级分类
        $where = [
            'is_del' => 0,
            'parent_id' => 0,
            'current_channel' => $this->channeltype
        ];
        $arctype_list = model('Arctype')->getAll('id, typename, dirpath', $where, 'id');

        // 新增栏目在指定的上一级栏目下
        $topid = !empty($arctype['topid']) ? intval($arctype['topid']) : 0;
        $grade = !empty($arctype['grade']) ? intval($arctype['grade']++) : 0;
        $parent_show = 0;
        $arctype_list2 = [];
        if (0 < intval($parent_id)) {
            $info = $this->arctype_db->field('parent_id, grade, topid')->find($parent_id);
            if (!empty($info)) {
                $grade = $info['grade'] + 1;
                $topid = !empty($info['topid']) ? $info['topid'] : $parent_id;
            }
            // 二级分类
            if (2 <= intval($grade)) {
                $where = [
                    'is_del' => 0,
                    'parent_id' => $info['parent_id'],
                    'current_channel' => $this->channeltype
                ];
                $parent_show = 1;
                $arctype_list2 = model('Arctype')->getAll('id, typename, dirpath', $where, 'id');
            }
        }

        // 返回数据
        return [
            'topid' => !empty($topid) ? intval($topid) : 0,
            'grade' => !empty($grade) ? intval($grade) : 0,
            'arctype' => !empty($arctype) ? $arctype : [],
            'parent_id' => !empty($parent_id) ? intval($parent_id) : 0,
            'predirpath' => !empty($predirpath) ? trim($predirpath) : '',
            'parent_show' => !empty($parent_show) ? $parent_show : 0,
            'arctype_list' => !empty($arctype_list) ? $arctype_list : [],
            'arctype_list2' => !empty($arctype_list2) ? $arctype_list2 : [],
        ];
    }

    // 获取商品分类数据
    private function getGoodsClassifyData()
    {
        // 分类名称处理
        $typename = addslashes(htmlspecialchars(strip_tags(strip_sql($this->paramArr['typename']))));
        // 分类纯拼音处理
        $dirname = $this->arctypeLogic->get_dirname($this->paramArr['typename'], '', $this->paramArr['id']);
        // 分类路径处理
        $dirpath = !empty($this->paramArr['dirpath']) ? rtrim($this->paramArr['dirpath'], '/') : '';

        // 返回数据
        $resultArr = [
            'topid' => !empty($this->paramArr['topid']) ? intval($this->paramArr['topid']) : 0,
            'parent_id' => !empty($this->paramArr['parent_id']) ? intval($this->paramArr['parent_id']) : intval($this->paramArr['topid']),
            'grade' => 0,
            'typename' => $typename,
            'dirname' => $dirname,
            'dirpath' => $dirpath . '/' . $dirname,
            'diy_dirpath' => $dirpath . '/' . $dirname,
            'litpic' => !empty($this->paramArr['litpic']) ? get_default_pic($this->paramArr['litpic']) : '',
            'ad_image' => !empty($this->paramArr['ad_image']) ? get_default_pic($this->paramArr['ad_image']) : '',
            'ad_host_id' => !empty($this->paramArr['ad_host_id']) ? intval($this->paramArr['ad_host_id']) : 0,
            'ad_link_id' => !empty($this->paramArr['ad_link_id']) ? intval($this->paramArr['ad_link_id']) : 0,
            'is_hidden' => !empty($this->paramArr['is_hidden']) ? intval($this->paramArr['is_hidden']) : 0,
        ];
        if (!empty($this->paramArr['topid'])) $resultArr['grade'] = 1;
        if (!empty($this->paramArr['parent_id'])) $resultArr['grade'] = 2;

        // 新增分类
        if ('insert' == $this->action) {
            $resultArr['sort_order'] = 100;
            $resultArr['add_time'] = $this->times;
            $resultArr['update_time'] = $this->times;
            $resultArr['tempview'] = 'view_product.htm';
            $resultArr['templist'] = 'lists_product.htm';
            $resultArr['channeltype'] = $this->channeltype;
            $resultArr['current_channel'] = $this->channeltype;
        }
        // 编辑分类
        else if ('update' == $this->action) {
            $resultArr['update_time'] = $this->times;
        }

        return $resultArr;
    }

    // 删除商品分类数据
    private function deleteGoodsClassifyData()
    {
        if (empty($this->paramArr['id'])) $this->error('请选择要删除的分类');

        // 查询分类级别
        $where = [
            'id' => intval($this->paramArr['id']),
            'current_channel' => $this->channeltype
        ];
        $grade = $this->arctype_db->where($where)->getField('grade');
        // 一级分类删除
        if (0 === intval($grade)) {
            $where = [
                'id|topid' => intval($this->paramArr['id']),
                'current_channel' => $this->channeltype
            ];
            $columnID = $this->arctype_db->where($where)->column('id');
        }
        // 二级分类删除
        else if (1 === intval($grade)) {
            $where = [
                'id|parent_id' => intval($this->paramArr['id']),
                'current_channel' => $this->channeltype
            ];
            $columnID = $this->arctype_db->where($where)->column('id');
        }
        // 三级分类删除
        else if (2 === intval($grade)) {
            $columnID = [intval($this->paramArr['id'])];
        }
        // 执行删除指定分类
        $where = [
            'id' => ['IN', $columnID],
            'current_channel' => $this->channeltype
        ];
        $deleteID = $this->arctype_db->where($where)->delete(true);
        // 删除分类后续操作
        if (!empty($deleteID)) {
            // // 更新分类所属商品为无分类
            // $where = [
            //     'typeid' => ['IN', $columnID],
            //     'channel' => $this->channeltype
            // ];
            // $update = [
            //     'typeid' => 0,
            //     'update_time' => getTime()
            // ];
            // Db::name('archives')->where($where)->update($update);
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}